# -*- coding: utf-8 -*-

from __future__ import unicode_literals

from django.shortcuts import render,render_to_response
from django.template import loader,Context
from django.http import HttpResponse,HttpResponseRedirect
from people.models import BlogPost,test01,User,Article,apiurl
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from .forms import UserForm
import json



@login_required(login_url="/login/")  
def archive1(request):
    post_answer = BlogPost.objects.all()
    request.encoding='utf-8'
    if request.method == 'POST':
        if 'searchname1' in request.POST:
            if request.POST['searchname1']:
                message = "你搜索的内容为: "+ request.POST['searchname1']
                test01.objects.create(title="search", content=request.POST['searchname1'])
            else:               
                message = "请输入内容"
    else:
        message="色即是空"
        post_answer = ""
    return render(request, 'search1.html', {'posts': post_answer,'message1':message})

def archivenews1(request):
    data = test01.objects.all()[:15]
    context = {  
        'data': data,  
    }
    return render(request,'search_result.html',context)



def api_receive(request):
    if request.method == 'GET':
        return render(request,'bootstarp_test.html')
    elif request.method == 'POST':
#       print request.POST
        if request.POST['url'] and request.POST['name']:
            apiurl.objects.create(name=request.POST['name'], url=request.POST['url'])
            resp = {'status': 200, 'result':0,'detail': 'Get success', 'message':'lalala'}
            my_response=HttpResponse(json.dumps(resp),content_type='application/json;charset=utf-8')
            my_response["Access-Control-Allow-Origin"] = "*"
            return my_response
    else:
        pass

def index(request):    
    return render(request,'index.html')

def test(request):
    return render(request, 'bootstarp_test.html')

'''
def login_old(request):
    if request.method =='POST':
        uf = UserForm(request.POST)
        err = 'invalid content,please input again!'
        if uf.is_valid():
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            user = User.objects.filter(username=username,password=password)
            if len(user)>=1:
                request.session['username']=username
                username = request.session.get('username','anybody')
                print username
                return render(request,'index.html')
            else:
                return HttpResponse('<h1>user/password something wrong</h1>')
        else:   
            return HttpResponse('<h1>%s</h1>' %(err))
    return render(request,'login.html')
'''

def user_login(request):
    if request.method =='POST':
        uf = UserForm(request.POST)
        err = 'invalid content,please input again!'
        if uf.is_valid():
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            user = auth.authenticate(request, username=username, password=password)
            if user is not None and user.is_active:
                request.session['username']=username
                auth.login(request, user)
                return render(request,'user_logout.html', {'username': username})
            else:
                return HttpResponse('<h1>user/password something wrong</h1>')
        else:   
            return HttpResponse('<h1>%s</h1>' %(err))
    return render(request,'login.html')

def user_logout(request):  
    auth.logout(request)  
    return HttpResponseRedirect('/')  



